package config

import (
	"encoding/base64"
	"encoding/json"
	"fmt"

	"gopkg.in/yaml.v2"
)

type (
	config struct {
		Harbor   harbor
		Redis    redisConfig
		Docker   docker
		Minio    minioConfig
		Database database
		GinMode  string `yaml:"GinMode"`
	}
	database struct {
		Host     string
		Port     int
		Username string
		Password string
		DBName   string
		SSLMode  string
	}
	harbor struct {
		Username string
		Password string
		Email    string
	}
	redisConfig struct {
		Addr     string
		Password string
		Key      map[string]string
		DB       int
	}
	docker struct {
		Host                      string
		DefaultRandomStringLength int
		Engine                    string
	}
	minioConfig struct {
		Host   string
		Key    string
		Secret string
		Secure bool
	}

	Container struct {
		Image string
		Id    string
		Name  string
	}
	CtfContainer struct {
		Container
		DestroyTimeStamp int64
		Flags            []string
		CallBack         string
		Ports            []string
	}
	LabContainer struct {
		Container
		IsVNC       bool
		CName       string
		PortMapping []string
	}
	LabContainers []LabContainer
	LabConfig     struct {
		TaskId           string
		Containers       LabContainers
		CallBack         string
		DestroyTimeStamp int64
		Code             int
	}

	BuildConfig struct {
		Filters  []string
		Force    bool
		Callback string
	}
	ImageBuildConfig struct {
		BuildConfig
		All bool
	}
	LabLoadConfig struct {
		ImageBuildConfig
	}
)

func (l LabContainer) String() string {
	response, _ := yaml.Marshal(l)
	return string(response)
}

func (l LabConfig) String() string {
	response, _ := yaml.Marshal(l)
	return string(response)
}

func (cc CtfContainer) String() string {
	response, _ := yaml.Marshal(cc)
	return string(response)
}

func (ibc ImageBuildConfig) String() string {
	response, _ := json.Marshal(ibc)
	return string(response)
}
func (c config) String() string {
	response, _ := yaml.Marshal(c)
	return string(response)
}

func (d database) URL() string {
	return fmt.Sprintf("host=%s port=%d user=%s "+
		"password=%s dbname=%s sslmode=disable",
		d.Host, d.Port, d.Username, d.Password, d.DBName)
}

func initAuth(username, password, email string) string {
	auth := map[string]string{
		"username": username,
		"password": password,
		"email":    email,
	}
	j, err := json.Marshal(auth)
	if err != nil {
		panic(err)
	}
	return base64.StdEncoding.EncodeToString(j)
}
